package background;

/**
 * 演示死锁
 */
public class MultiThreadError2 implements Runnable {

    int flag = 1;
    static Object o1 = new Object();
    static Object o2 = new Object();

    public static void main(String[] args) {
        MultiThreadError2 multiThreadError1 = new MultiThreadError2();
        MultiThreadError2 multiThreadError2 = new MultiThreadError2();

        multiThreadError1.flag = 1;
        multiThreadError2.flag = 0;


        new Thread(multiThreadError1).start();
        new Thread(multiThreadError2).start();

    }


    @Override
    public void run() {
        System.out.println("flag = "+flag);

        if (flag == 1){
            synchronized (o1){
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (o2){
                    System.out.println("flag = 1");
                }

            }
        }

        if (flag == 0){
            synchronized (o2){
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (o1){
                    System.out.println("flag = 0");
                }

            }
        }
    }
}
